<template>
  <div @click="handleCloseComboBox">
    <el-dialog title="新增账号" :visible.sync="value" width="30%" class="entityDialog" :before-close="closeDialog">
      <el-form ref="ruleForm" size="medium">
        <!--搜索-->
        <el-form-item class="search-box">
          <el-input v-model="keyword">
            <el-button v-if="isAddAccount" slot="append" @click.stop="getPropertiesByUri">添加</el-button>
            <el-button v-else slot="append" icon="el-icon-search" @click.stop="handleSearh(1)"></el-button>
          </el-input>
          <el-alert v-show="input_error" title="您还没有填写关键词" type="error" @close="handlerClearError"> </el-alert>
          <div v-show="isSearchResult_show" class="search-result-container">
            <ul>
              <li v-for="(account,index) in accountList" :key="index" class="search-result-box" @click.stop="handleChooseAccount(account)">
                <div class="search-result-item">
                  <img class="search-result-img" :src="account.iconUrl" alt="">
                </div>
                <div class="search-result-content">
                  <span class="displayName">{{account.showName?account.showName:account.displayName}}</span>
                  <span>{{account.name}}</span>
                </div>
              </li>
              <el-pagination v-if="accountList.length>0" class="page-container" background layout="prev, next,total" :current-page="page" :page-size="page_size" @current-change="handlerChangePage">
              </el-pagination>
            </ul>
          </div>
        </el-form-item>
        <el-form-item class="selected-account-container" label="已选择的账号：" v-if="current_selectd_account!=''">
          <span class="selected-account">{{current_selectd_account.showName}}({{current_selectd_account.name}})</span>
        </el-form-item>
        <el-form-item v-if="isAddAccount" label="实体类型">
          <el-input v-model="current_selectd_node_name" :readonly="true">
            <i class=" pointer el-icon-arrow-down el-input__icon" slot="suffix" @click.stop="showTree"> </i>
          </el-input>
          <div v-show="isShow" class="treeDemo">
            <el-tree ref="tree" :default-expand-all="true" :props="defaultProps" :expand-on-click-node="false" :data="treeData" @node-click="handleNodeClick" :render-content="renderContent">
            </el-tree>
          </div>
          <el-alert v-show="account_type_error" title="请选择实体类型" type="error" @close="handlerClearError"> </el-alert>
        </el-form-item>
        <template v-for="(item,index) in propertyList">
          <div v-if="isAddAccount" :key="index">
            <template v-if="item.propertyType==='GisData'">
              <el-form-item label-width="80px" :label="item.displayname" :required="item.representative==='1'">
                <el-input placeholder="经度" v-model="item.value.longitude" style="width:25%"></el-input>
                <el-input placeholder="纬度" v-model="item.value.latitude" style="width:25%"></el-input>
                <el-input placeholder="地理位置描述" v-model="item.value.address" style="width:25%"></el-input>
              </el-form-item>
            </template>
            <template v-else-if="item.propertyType==='DateTime'">
              <el-form-item label-width="80px" :label="item.displayname" :required="item.representative==='1'">
                <el-date-picker type="datetime" v-model="item.value" value-format="yyyy-MM-dd HH:mm:ss" style="width:40%" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </template>
            <template v-else-if="item.propertyType==='TimeInterval'">
              <el-form-item  label-width="80px" :label="item.displayname" :required="item.representative==='1'">
                <el-date-picker type="datetime" v-model="item.value.startTime" value-format="yyyy-MM-dd HH:mm:ss" style="width:40%" placeholder="请输入开始日期">
                </el-date-picker>
                <el-date-picker type="datetime" v-model="item.value.endTime" value-format="yyyy-MM-dd HH:mm:ss" style="width:40%" placeholder="请输入结束日期">
                </el-date-picker>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item label-width="80px" :label="item.displayname" :required="item.representative==='1'">
                <el-input :placeholder="'请输入'+item.displayname" v-model="item.value" style="width:60%"></el-input>
              </el-form-item>
            </template>
          </div>
        </template>
        <!--关系-->
        <template v-if="current_selectd_account!==''||relation_options.length>0">
          <!-- <el-form-item label="关系类型"  label-width="80px" >
          <el-select v-model="relation_type"  placeholder="请选择">
            <el-option label="现有关系" value="current"></el-option>
            <el-option label="新建关系" value="add"></el-option>
          </el-select>
        </el-form-item> -->
          <el-form-item label="选择关系" label-width="80px">
            <el-select v-model="current_relation" placeholder="请选择" value-key="displayname">
              <el-option v-for="(item,index) in relation_options" :key="index" :label="item.displayname" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间" label-width="80px">
            <el-date-picker type="datetime" v-model="timeStart" value-format="yyyy-MM-dd HH:mm:ss" style="width:45%" placeholder="请选择开始时间">
            </el-date-picker>
            <el-date-picker type="datetime" v-model="timeEnd" value-format="yyyy-MM-dd HH:mm:ss" style="width:45%" placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :disabled="current_relation===''">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import util from '@/utils'
import { saveEdge, searchFullTextList, findOperateProperties, findAllWithBizGroupAsMap, saveInstance, getOperateLinks, relate2Objects } from '@/api/archives'
export default {
    name: 'entityOrEventEditor',
    data () {
        return {
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'displayname'
            },
            // 属性列表
            propertyList: '',
            // 当前选择的账号属性类型
            current_selectd_node: '',
            // 当前选择的账号属性类型名称
            current_selectd_node_name: '无',
            // 是否显示账号属性下拉框
            isShow: false,
            // 当前关系
            current_relation: '',
            // 开始时间
            timeStart: new Date(),
            // 结束时间
            timeEnd: new Date(),
            // 关系选项
            relation_options: [],
            // 是否显示搜索结果
            isSearchResult_show: false,
            // 输入框错误输入提示标识符
            input_error: false,
            // 账号类型错误输入提示标识符
            account_type_error: false,
            // 搜索关键字
            keyword: '',
            // 账户列表
            accountList: [],
            page: 1,
            // 每页条数
            page_size: 10,
            // 当前选中的账户
            current_selectd_account: '',
            // 是否添加账号
            isAddAccount: false
            // 关系类型(现有关系/新建关系)
            // relation_type: 'current'
        }
    },
    props: {
        value: Boolean,
        objType: String,
        rowkey: String,
        objectUri: {
            type: String,
            default: ''
        }
    },
    watch: {
        value: function (val, newVal) {
            this.$nextTick(() => {
                // 移除表单验证结果
                this.$refs.ruleForm.clearValidate()
            })
        },
        keyword: function (val, newVal) {
            this.input_error = false
            this.isAddAccount = false
            this.propertyList = []
            this.relation_options = []
            this.current_selectd_node_name = ''
            this.current_selectd_node = ''
            // 开始时间
            this.timeStart = new Date()
            // 结束时间
            this.timeEnd = new Date()
        }
    },
    methods: {
    // 显示对象树
        showTree () {
            this.loadTree()
            this.isShow = true
        },
        getRelationList (uri) {
            getOperateLinks({ objectUri: uri }).then(response => {
                this.relation_options = response.data
            })
        },
        // 加载左侧菜单树
        loadTree () {
            let params = {
                groupList: ['socialaccount', 'keyfigures', 'focusgroup']
            }
            findAllWithBizGroupAsMap(params).then(data => {
                this.treeData = util.parseKeyData(data)
            })
        },
        handleNodeClick (data, node) {
            if (node.level === 1) {
                return false
            }
            this.current_selectd_node = data
            this.current_selectd_node_name = this.current_selectd_node.displayname
            this.isShow = false
            this.account_type_error = false
            this.getPropertiesByUri()
        },
        // 根据uri获取属性
        async getPropertiesByUri () {
            this.current_selectd_account = ''
            if (this.current_selectd_node === '') {
                this.account_type_error = true
                return
            }
            let uri = this.current_selectd_node.uri
            let propertyList = await findOperateProperties({ uri: uri })
            // 过滤属性
            propertyList = propertyList.filter(item => item.allowed === '1' && item.representative === '1')
            if (propertyList.length === 0) {
                this.$message.error('该对象没有属性,请重新选择')
                this.propertyList = []
            } else {
                this.buildProperty(propertyList)
                this.getRelationList(uri)
            }
            this.handleCloseComboBox()
        },
        // 搜索
        async handleSearh (page) {
            if (this.keyword === '') {
                this.input_error = true
                return
            }
            // let objectList = []
            // if (this.current_selectd_node !== '') {
            //     objectList.push(this.current_selectd_node.uri)
            // }
            let param = {
                keywords: [this.keyword],
                // objectList: objectList,
                objectType: 'socialaccount,keyfigures,focusgroup',
                curpage: page,
                persize: this.page_size
            }
            this.accountList = await searchFullTextList(param)
            this.current_selectd_account = ''
            this.current_relation = ''
            this.relation_options = []
            this.propertyList = []
            if (this.accountList.length === 0) {
                this.isAddAccount = true
            } else {
                this.isSearchResult_show = true
            }
        },
        // 当前页改变时会触发
        handlerChangePage (val) {
            this.handleSearh(val)
            this.page = val
        },
        // 清除输入框输入错误提示
        handlerClearError () {
            this.input_error = false
            this.account_type_error = false
        },
        // 选择查询的账户
        handleChooseAccount (account) {
            this.getRelationList(account.objectUri)
            this.current_selectd_account = account
            this.isSearchResult_show = false
            this.propertyList = []
        },
        // 构建属性
        buildProperty (data) {
            this.propertyList = data.map(element => {
                if (element.propertyType === 'GisData') {
                    element.value = { address: '', longitude: '', latitude: '' }
                } else if (element.propertyType === 'TimeInterval') {
                    element.value = { startTime: '', endTime: '' }
                } else {
                    element.value = ''
                }
                return element
            })
        },
        handleCloseComboBox () {
            this.isShow = false
            this.isSearchResult_show = false
        },
        // 表单提交
        handleSubmit () {
            let linkUri = this.current_relation.uri
            if (this.current_selectd_account !== '') {
                // 给两个对象关联一条已存在的关系
                relate2Objects({
                    objectSourceUri: this.objectUri,
                    objectTargetUri: this.current_selectd_account.objectUri,
                    linkUri: linkUri
                }).then(response => {
                    let fromRowkey = ''
                    let toRowkey = ''
                    if (this.objType === 'com.scistor.object.entity') {
                        fromRowkey = this.current_selectd_account.rowkey
                        toRowkey = this.rowkey
                    } else {
                        fromRowkey = this.rowkey
                        toRowkey = this.current_selectd_account.rowkey
                    }
                    saveEdge({
                        fromRowkey: fromRowkey,
                        toRowkey: toRowkey,
                        linkUri: linkUri,
                        timeStart: new Date(this.timeStart).getTime(),
                        timeEnd: new Date(this.timeStart).getTime()
                    }).then(response => {
                        this.$message.success('新增成功')
                        this.closeDialog()
                        setTimeout(() => {
                            this.$emit('getAssociationEntity', this.rowkey)
                        }, 3000)
                    })
                })
            } else {
                let objectUri = this.current_selectd_node.uri
                let param = {
                    objectUri: objectUri,
                    propertyList: [],
                    // 边的关系
                    edge: {
                        fromRowkey: this.rowkey,
                        linkUri: linkUri,
                        timeStart: new Date(this.timeStart).getTime(),
                        timeEnd: new Date(this.timeStart).getTime()
                    }
                }
                let propertyList = this.propertyList
                for (let i = 0; i < propertyList.length; i++) {
                    let element = propertyList[i]
                    let displayed = element.displayed !== '0'
                    // 属性类型为地理数据类型
                    if (element.propertyType === 'GisData') {
                        if (element.representative === '1') {
                            if (util.verifyValue(element.propertyType, element.value, element.displayname)) {
                                param.propertyList.push({
                                    propertyUri: element.propertyUri,
                                    propertyType: element.propertyType,
                                    address: element.value.address,
                                    longitude: element.value.longitude,
                                    latitude: element.value.latitude,
                                    label: true,
                                    displayed: displayed
                                })
                            } else {
                                return false
                            }
                        } else {
                            if (element.value.address !== '') {
                                if (util.verifyValue(element.propertyType, element.value, element.displayname)) {
                                    param.propertyList.push({
                                        propertyUri: element.propertyUri,
                                        propertyType: element.propertyType,
                                        address: element.value.address,
                                        longitude: element.value.longitude,
                                        latitude: element.value.latitude,
                                        displayed: displayed
                                    })
                                } else {
                                    return false
                                }
                            }
                        }
                    } else if (element.propertyType === 'TimeInterval') {
                        // 属性类型为时间区间
                        if (element.representative === '1') {
                            if (util.verifyValue(element.propertyType, element.value, element.displayname)) {
                                param.propertyList.push({
                                    propertyUri: element.propertyUri,
                                    propertyType: element.propertyType,
                                    timeStart: new Date(element.value.startTime).getTime(),
                                    timeEnd: new Date(element.value.endTime).getTime(),
                                    label: true,
                                    displayed: displayed
                                })
                            } else {
                                return false
                            }
                        } else {
                            if (element.value.startTime !== '' && element.value.endTime !== '') {
                                if (this.verifyTime(element.value)) {
                                    param.propertyList.push({
                                        propertyUri: element.propertyUri,
                                        propertyType: element.propertyType,
                                        timeStart: new Date(element.value.startTime).getTime(),
                                        timeEnd: new Date(element.value.endTime).getTime(),
                                        displayed: displayed
                                    })
                                } else {
                                    return false
                                }
                            }
                        }
                    } else {
                        if (element.representative === '1') {
                            if (element.value === '') {
                                this.$message.error(
                                    `${element.displayname}为代表属性,属性值不能为空!`
                                )
                                return false
                            } else {
                                if (util.verifyValue(element.propertyType, element.value, element.displayname)) {
                                    let value = element.value
                                    if (element.propertyType === 'DateTime') {
                                        value = new Date(element.value).getTime()
                                    }
                                    param.propertyList.push({
                                        propertyUri: element.propertyUri,
                                        propertyType: element.propertyType,
                                        value: value,
                                        label: true,
                                        displayed: displayed
                                    })
                                } else {
                                    return false
                                }
                            }
                        } else {
                            if (element.value !== '') {
                                // 验证输入值是否合法
                                if (util.verifyValue(element.propertyType, element.value, element.displayname)) {
                                    let value = element.value
                                    if (element.propertyType === 'DateTime') {
                                        value = new Date(element.value).getTime()
                                    }
                                    param.propertyList.push({
                                        propertyUri: element.propertyUri,
                                        propertyType: element.propertyType,
                                        value: value,
                                        displayed: displayed
                                    })
                                } else {
                                    return false
                                }
                            }
                        }
                    }
                }
                // 给两个对象关联一条已存在的关系
                relate2Objects({
                    objectSourceUri: this.objectUri,
                    objectTargetUri: objectUri,
                    linkUri: linkUri
                }).then(response => {
                    saveInstance(param).then(response => {
                        this.$message({ message: '新增成功!', type: 'success' })
                        this.closeDialog()
                        setTimeout(() => {
                            this.$emit('getAssociationEntity', this.rowkey)
                        }, 3000)
                    })
                })
            }
        },
        // 验证时间
        verifyTime (object) {
            if (object.startTime === '') {
                this.$message.error('请输入开始时间!')
                return false
            }
            if (object.endTime === '') {
                this.$message.error('请输入结束时间!')
                return false
            }
            if (new Date(object.startTime).getTime() > new Date(object.endTime).getTime()) {
                this.$message.error('开始时间不能大于结束时间!')
                return false
            }
            return true
        },
        renderContent (h, { node, data }) {
            let img
            if (!util.isEmpty(data.icon)) {
                img = (
                    <img src={data.icon} class="userIcon" width="16px" height="16px" />
                )
            }
            return (
                <p>
                    {img}
                    <span style="margin-left:10px;">{node.label}</span>
                </p>
            )
        },

        // 关闭对话框
        closeDialog () {
            this.$emit('input', false)
            this.treeData = []
            this.relation_options = []
            this.keyword = ''
            this.isShow = false
            this.isSearchResult_show = false
            this.input_error = false
            this.account_type_error = false
            this.current_selectd_account = ''
            this.current_selectd_node = ''
            this.current_selectd_node_name = ''
            this.propertyList = ''
            this.timeStart = new Date()
            this.timeEnd = new Date()
            this.$refs.ruleForm.clearValidate()
        }
    }
}
</script>
<style lang="less"  >
.entityDialog {
  min-height: 240px;
  .el-alert {
    background-color: transparent;
  }
  .search-box {
    margin-bottom: 0px !important;
  }
  .selected-account-container {
    margin-bottom: 15px !important;
    .selected-account {
      color: #1169c4;
      font-weight: bold;
    }
  }
  .el-checkbox__inner {
    border-radius: 10px;
  }
  .userIcon {
    position: relative;
    top: 10px;
  }
  .search-result-container {
    width: 100%;
    position: absolute;
    background-color: #fff;
    z-index: 33;
    border: 1px solid #e0e0e0;
    padding: 5px 0 5px 5px;
    .search-result-box {
      padding: 5px 0 5px 10px;
      border-bottom: 1px solid #eee;
      display: flex;
      box-sizing: border-box;
      cursor: pointer;
      &:hover {
        background: #ecf5ff;
      }
      .search-result-item {
        margin-right: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .search-result-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        .displayName {
          color: #08c;
        }
        span {
          line-height: 18px;
        }
      }
      .search-result-img {
        height: 36px;
      }
    }
    .page-container {
      margin-top: 16px;
      text-align: center;
    }
  }
  .treeDemo {
    width: 100%;
    position: absolute;
    background-color: #fff;
    z-index: 33;
    border: 1px solid #e0e0e0;
    padding: 10px 0 30px;
    .opreation {
      margin-top: 10px;
      text-align: right;
      padding-right: 10px;
      .el-button {
        padding: 5px 15px;
        line-height: 16px;
      }
    }
  }
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
